<template>
	<div>
	<!-- 面包屑导航 -->
	<el-breadcrumb separator-class="el-icon-arrow-right">
	  <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
	  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
	  <el-breadcrumb-item>分类参数</el-breadcrumb-item>
	</el-breadcrumb>
	
	<!-- 卡片视图 -->
	<el-card class="box-card">
		 <el-alert
		    title="注意: 只允许为三级分类设置参数"
		    type="warning"
		    show-icon
			:closable="false">
		  </el-alert>
		  <!-- 选择商品分类区域 -->
		  <el-row class="cat_opt">
			  <el-col>
				    <span>请选择商品分类：</span>
					<!-- 级联选择框 -->
					 <el-cascader
					    v-model="selectedCateKeys"
					    :options="catelist"
					    :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id' }"
					    @change="handleChange"></el-cascader>
			  </el-col>
			  <el-col style="margin-top: 20px;">
				   <el-tabs v-model="activeName" @tab-click="handleClick">
				      <el-tab-pane label="动态参数" name="many">
						  <el-button @click="dialogVisible = true" size="mini" type="primary" :disabled="btnDisabled">添加参数</el-button>
						  <el-table
						     :data="manyTabData"
						     stripe
							  border
						     style="width: 100%">
						  					  <el-table-column type="expand">
												  <template slot-scope="scope">
															  <el-tag  v-for="(item,i) in scope.row.attr_vals" :key="i" type="success" :closable="true" @close="tagHandleClose(i,scope.row)">{{item}}</el-tag>
															 <el-input
															   class="input-new-tag"
															   v-if="scope.row.inputVisible"
															   v-model="scope.row.inputValue"
															   ref="saveTagInput"
															   size="small"
															   @keyup.enter.native="handleInputConfirm(scope.row)"
															   @blur="handleInputConfirm(scope.row)"
															 >
															 </el-input>
															 <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
												  </template>
						  					  </el-table-column>
						  					  <el-table-column type="index" label="#">
						  					  </el-table-column>
						     <el-table-column prop="attr_name" label="参数名称">
						     </el-table-column>
						  					  <el-table-column  label="操作">
						  						  <template slot-scope='scope'>
						  							  <el-button @click="editParam(scope.row)"  size="mini" type="primary" icon="el-icon-edit" circle></el-button>
						  							  <el-button @click="deleteParam(scope.row)" size="mini" type="danger" icon="el-icon-delete" circle></el-button>
						  						  </template>
						  					  </el-table-column>
						   </el-table>
					  </el-tab-pane>
				      <el-tab-pane label="静态属性" name="only">
						  <el-button @click="dialogVisible = true" size="mini" type="primary" :disabled="btnDisabled">添加属性</el-button>
						  <el-table
						     :data="onlyTabData"
						     stripe
						     style="width: 100%">
						  					  <el-table-column type="expand">
												  <template slot-scope="scope">
												  		  <el-tag  v-for="(item,i) in scope.row.attr_vals" :key="i" type="success" :closable="true" @close="tagHandleClose(i,scope.row)">{{item}}</el-tag>
												  		 <el-input
												  		   class="input-new-tag"
												  		   v-if="scope.row.inputVisible"
												  		   v-model="scope.row.inputValue"
												  		   ref="saveTagInput"
												  		   size="small"
												  		   @keyup.enter.native="handleInputConfirm(scope.row)"
												  		   @blur="handleInputConfirm(scope.row)"
												  		 >
												  		 </el-input>
												  		 <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
												  </template>
						  					  </el-table-column>
						  					  <el-table-column type="index">
						  					  </el-table-column>
						     <el-table-column prop="attr_name" label="属性名称">
						     </el-table-column>
						  					  <el-table-column  label="操作">
						  						  <template slot-scope='scope'>
						  							  <el-button @click="editParam(scope.row)" size="mini" type="primary" icon="el-icon-edit" circle></el-button>
						  							  <el-button @click="deleteParam(scope.row)" size="mini" type="danger" icon="el-icon-delete" circle></el-button>
						  						  </template>
						  					  </el-table-column>
						   </el-table>
					  </el-tab-pane>
				    </el-tabs>
			  </el-col> 
		 </el-row>
				 		
	</el-card>
     <el-dialog
       :title="添加"
       :visible.sync="dialogVisible"
       width="30%"
       :before-close="handleClose">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules">
		  <el-form-item prop="attr_name" :label="addFormText">
		<el-input class="dialogInput" v-model="addForm.attr_name" type="text"></el-input>
		  </el-form-item>
	  </el-form>
       <span slot="footer" class="dialog-footer">
         <el-button @click="dialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="addParams">确 定</el-button>
       </span>
     </el-dialog>
	 <el-dialog
        title="修改"
        :visible.sync="paramDialogVisible"
        width="30%"
        :before-close="paramHandleClose">
		      <el-form  ref="editFormRef" :model="edit" :rules="addFormRules">
		  <el-form-item prop="attr_name" label="参数/属性名称:">
		<el-input class="dialogInput" v-model="edit.attr_name"></el-input>
		 </el-form-item>
	  </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="paramDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="paramSubmit">确 定</el-button>
        </span>
      </el-dialog>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				catelist:[],
				//级联选择框选中的数组
				selectedCateKeys:[],
				//被激活的标签页
				activeName:'many',
				manyTabData:[],
				onlyTabData:[],
				dialogVisible:false,
				inputVisible:false,
				paramDialogVisible:false,
				edit:{},
				inputValue:'',
				addForm:{ 
					attr_name:'' 
					},
				addFormRules:{
					attr_name:[{ required :true ,message: '请输入参数',trigger:'blur' }]
				}
			}
		},
		created() {
			this.getCateList()
		},
		methods:{
			async getCateList(){
				const { data:res } = await this.$http.get('categories')
				if( res.meta.status !== 200 )
				return this.$message.error('获取失败')
				this.catelist = res.data
				console.log(this.catelist)
			},
			//级联选择框点击事件
			async handleChange(){
			this.getParamsList()
			},
			//标签页选择事件
			async handleClick(){
				console.log(this.activeName)
				console.log(this.selectedCateKeys)
				this.getParamsList()
			},
			//获取参数信息
			async getParamsList(){
				if( this.selectedCateKeys.length !== 3 )
				{
				this.selectedCateKeys = []
				this.manyTabData = []
				return this.onlyTabData = []
				}
				const { data:res } = await this.$http.get('categories/'+this.CateID+'/attributes',{ params:{ sel:this.activeName } })
				console.log(res)
				if( res.meta.status !== 200 )
				return this.$message.error(res.meta.msg)
				res.data.forEach( item => { item.attr_vals = ( item.attr_vals !== '' ? item.attr_vals.split(','):[] ), item.inputVisible = false, item.inputValue = ''})
				console.log(res.data)
				if( this.activeName === 'many' )
					this.manyTabData = res.data
				else
				    this.onlyTabData = res.data
			},
			//监听对话框关闭
			handleClose(){
				this.$refs.addFormRef.resetFields()
				this.dialogVisible = false
			},
			paramHandleClose(){
				this.paramDialogVisible = false
				this.$refs.editFormRef.resetFields()
			},
			addParams(){
				this.$refs.addFormRef.validate(async valid => 
				{
					if( !valid ) return
					const { data:res } = await this.$http.post('categories/'+this.CateID+'/attributes',{
						attr_name: this.addForm.attr_name,
						attr_sel: this.activeName
					})
					if( res.meta.status !== 201 )
					return this.$message.error(res.meta.msg)
					console.log(res)
					this.$message.success(res.meta.msg)
					this.getParamsList()
					this.dialogVisible = false
				})
			},
			//添加标签处理函数
			async handleInputConfirm(row){
				if( row.inputValue.trim().length === 0 )
				{
					row.inputValue = ''
				row.inputVisible = false
				return
				}
				else
				{
					console.log(row.attr_vals)
					row.attr_vals.push(row.inputValue)
					this.saveAttrValues(row)
					row.inputValue = ''
					row.inputVisible = false
				}
			},
			showInput(row){
				row.inputVisible = !row.inputVisible
				 this.$nextTick(_ => {
				          this.$refs.saveTagInput.$refs.input.focus();
				        })
			},
			tagHandleClose(i,row){
				row.attr_vals.splice(i,1)
				this.saveAttrValues(row)
			},
			//处理编辑参数保存到数据库
			 async saveAttrValues(row){
				 const { data:res} = await this.$http.put('categories/'+this.CateID+'/attributes/'+row.attr_id,{
				 	attr_name:row.attr_name,
				 	attr_sel :row.attr_sel,
				 	attr_vals: row.attr_vals.join(',')
				 })
				 if( res.meta.status !== 200 )
				   return this.$message.error(res.meta.msg)
				  this.$message.success('修改成功')
			 },
			 editParam(row){
				  this.paramDialogVisible = true
				  console.log(name)
				  this.edit = row
			 },
			  async paramSubmit(){
				 this.saveAttrValues(this.edit)
				 this.getCateList()
				 this.paramDialogVisible = false
			 },
			 async deleteParam(row){
				   this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'warning'
			        }).then(async() => {
					 const {data:res} = await this.$http.delete('categories/'+this.CateID+'/attributes/'+ row.attr_id)
					 console.log(res)
					 if( res.meta.status !== 200 )
					 return res.meta.msg 
			          this.$message({
			            type: 'success',
			            message: '删除成功!'
			          });
					  this.getCateList()
					  this.getParamsList()
			        }).catch(() => {
			          this.$message({
			            type: 'info',
			            message: '已取消删除'
			          });          
			        });
			 }
		},
		computed:{
			//是否禁用按钮
			btnDisabled(){
				if ( this.selectedCateKeys.length !== 3 )
				return true
				else
				return false
			},
			CateID(){
				if ( this.selectedCateKeys.length === 3 )
				return this.selectedCateKeys[2]
				else
				return null
			},
			dialogTitle(){
				if ( this.activeName === 'many' )
				return '动态参数'
				else
				return '静态属性'
			},
			addFormText(){
				if ( this.activeName === 'many' )
				return '添加参数'
				else
				return '添加属性'
			}
		}
	}
</script>

<style lang="less" scoped>
	.cat_opt{
		margin: 20px;
	}
	
	.el-tag{
		margin: 10px;
	}
	.el-input{
		width: 120px;
		margin: 10px;
	}
	.dialogInput{
		width: 70%;
	}
</style>
